#!/bin/bash

set -e

# 包信息
PROJECT_NAME="drwtestlinux"
VERSION="1.3"
MAINTAINER="huwenyupeter <huwenyupeter@qq.com>"
DESCRIPTION="存储设备写入可靠性验证测试工具"

# 目录设置
BUILD_DIR="build"
DIST_DIR="dist"
TOOLCHAIN_DIR="cmake"

# 获取当前工作目录的绝对路径
CURRENT_DIR=$(pwd)

# 创建构建和分发目录
mkdir -p ${BUILD_DIR}
mkdir -p ${DIST_DIR}/x86_64
mkdir -p ${DIST_DIR}/aarch64

# 清理之前的构建
rm -rf ${BUILD_DIR}/*
rm -rf ${DIST_DIR}/x86_64/*
rm -rf ${DIST_DIR}/aarch64/*

echo "=== 在Kali Linux上构建并打包 ${PROJECT_NAME} v${VERSION} ==="

# 检查并安装必要的工具
echo "检查必要的工具..."
if ! command -v cmake &> /dev/null; then
    echo "安装cmake..."
    sudo apt-get update
    sudo apt-get install -y cmake
fi

if ! command -v pkg-config &> /dev/null; then
    echo "安装pkg-config..."
    sudo apt-get update
    sudo apt-get install -y pkg-config
fi

if ! command -v dpkg-deb &> /dev/null; then
    echo "安装dpkg-dev..."
    sudo apt-get update
    sudo apt-get install -y build-essential dh-make debhelper devscripts dpkg-dev
fi

if ! command -v rpmbuild &> /dev/null; then
    echo "安装rpm..."
    sudo apt-get install -y rpm
fi

if ! command -v aarch64-linux-gnu-gcc &> /dev/null; then
    echo "安装aarch64交叉编译工具链..."
    sudo apt-get install -y gcc-aarch64-linux-gnu g++-aarch64-linux-gnu
fi

# 函数：构建指定架构
build_architecture() {
    local arch=$1
    local toolchain=$2
    local build_dir="${BUILD_DIR}/${arch}"
    
    echo "构建 ${arch} 架构..."
    
    mkdir -p ${build_dir}
    cd ${build_dir}
    
    # 配置CMake
    cmake ../.. \
        -DCMAKE_TOOLCHAIN_FILE=../../${TOOLCHAIN_DIR}/${toolchain} \
        -DCMAKE_BUILD_TYPE=Release \
        -DCMAKE_INSTALL_PREFIX=/usr
    
    # 编译
    make -j$(nproc)
    
    cd ../..
    
    echo "${arch} 构建完成"
}

# 函数：创建DEB包
create_deb_package() {
    local arch=$1
    local deb_arch=$2
    local dist_subdir=$3
    
    local package_dir="${BUILD_DIR}/deb/${PROJECT_NAME}_${VERSION}_${deb_arch}"
    
    mkdir -p ${package_dir}/DEBIAN
    mkdir -p ${package_dir}/usr/bin
    mkdir -p ${package_dir}/usr/share/doc/${PROJECT_NAME}
    
    # 检查可执行文件是否存在
    if [ ! -f "${BUILD_DIR}/${arch}/${PROJECT_NAME}" ]; then
        echo "错误: 未找到 ${BUILD_DIR}/${arch}/${PROJECT_NAME} 文件"
        return 1
    fi
    
    # 复制可执行文件
    cp ${BUILD_DIR}/${arch}/${PROJECT_NAME} ${package_dir}/usr/bin/
    chmod 755 ${package_dir}/usr/bin/${PROJECT_NAME}
    
    # 创建控制文件
    cat > ${package_dir}/DEBIAN/control << EOF
Package: ${PROJECT_NAME}
Version: ${VERSION}
Architecture: ${deb_arch}
Maintainer: ${MAINTAINER}
Description: ${DESCRIPTION}
Depends: libc6 (>= 2.28)
Priority: optional
Section: utils
EOF
    
    # 复制文档
    if [ -f README.md ]; then
        cp README.md ${package_dir}/usr/share/doc/${PROJECT_NAME}/
    fi
    if [ -f LICENSE ]; then
        cp LICENSE ${package_dir}/usr/share/doc/${PROJECT_NAME}/copyright
    fi
    
    # 构建DEB包
    dpkg-deb --build ${package_dir} ${DIST_DIR}/${dist_subdir}/${PROJECT_NAME}_${VERSION}_${deb_arch}.deb
    
    echo "创建了 ${DIST_DIR}/${dist_subdir}/${PROJECT_NAME}_${VERSION}_${deb_arch}.deb"
    return 0
}

# 函数：创建RPM包
create_rpm_package() {
    local arch=$1
    local rpm_arch=$2
    local dist_subdir=$3
    
    # 使用绝对路径
    local rpm_dir="${CURRENT_DIR}/${BUILD_DIR}/rpm/${arch}"
    local build_dir="${rpm_dir}/BUILD"
    local rpmbuild_dir="${rpm_dir}/RPMS"
    local spec_dir="${rpm_dir}/SPECS"
    local source_dir="${rpm_dir}/SOURCES"
    
    mkdir -p ${build_dir} ${rpmbuild_dir} ${spec_dir} ${source_dir}
    
    # 检查可执行文件是否存在
    if [ ! -f "${CURRENT_DIR}/${BUILD_DIR}/${arch}/${PROJECT_NAME}" ]; then
        echo "错误: 未找到 ${BUILD_DIR}/${arch}/${PROJECT_NAME} 文件"
        return 1
    fi
    
    # 修复日期格式问题 - 使用英文格式
    local changelog_date=$(LANG=C date +"%a %b %d %Y")
    
    # 创建spec文件 - 使用绝对路径
    cat > ${spec_dir}/${PROJECT_NAME}.spec << EOF
Name: ${PROJECT_NAME}
Version: ${VERSION}
Release: 1%{?dist}
Summary: ${DESCRIPTION}
License: GPL-3.0
URL: https://github.com/huwenyupeter/drwtest
Packager: ${MAINTAINER}
BuildArch: ${rpm_arch}
Requires: glibc >= 2.28

%description
${DESCRIPTION}

%prep
# 不需要准备阶段，我们直接安装

%build
# 不需要构建阶段，我们使用预编译的二进制文件

%install
# 创建安装目录
mkdir -p %{buildroot}/usr/bin
mkdir -p %{buildroot}/usr/share/doc/%{name}

# 复制可执行文件 - 使用绝对路径
cp ${CURRENT_DIR}/${BUILD_DIR}/${arch}/${PROJECT_NAME} %{buildroot}/usr/bin/${PROJECT_NAME}
chmod 755 %{buildroot}/usr/bin/${PROJECT_NAME}

# 复制文档
if [ -f "${CURRENT_DIR}/README.md" ]; then
    cp ${CURRENT_DIR}/README.md %{buildroot}/usr/share/doc/%{name}/
fi
if [ -f "${CURRENT_DIR}/LICENSE" ]; then
    cp ${CURRENT_DIR}/LICENSE %{buildroot}/usr/share/doc/%{name}/copyright
fi

%files
/usr/bin/${PROJECT_NAME}
/usr/share/doc/%{name}/*

%changelog
* ${changelog_date} ${MAINTAINER} - ${VERSION}-1
- 初始版本
EOF
    
    # 设置RPM环境变量
    export RPM_TOPDIR="${rpm_dir}"
    
    # 修复RPM数据库权限问题 - 使用用户目录
    mkdir -p ${HOME}/.rpmdb
    if [ ! -f ${HOME}/.rpmdb/Packages ]; then
        echo "初始化RPM数据库..."
        rpm --initdb --dbpath=${HOME}/.rpmdb
    fi
    
    # 检查RPM数据库状态（使用正确的命令）
    echo "检查RPM数据库状态..."
    rpm --dbpath=${HOME}/.rpmdb -qa >/dev/null 2>&1 && echo "RPM数据库正常" || echo "RPM数据库有问题"
    
    # 构建RPM包，使用用户数据库
    echo "开始构建RPM包..."
    if rpmbuild --define "_topdir ${rpm_dir}" \
                --define "_builddir ${build_dir}" \
                --define "_rpmdir ${rpmbuild_dir}" \
                --define "_sourcedir ${source_dir}" \
                --define "_specdir ${spec_dir}" \
                --define "_srcrpmdir ${rpm_dir}/SRPMS" \
                --define "_buildrootdir ${build_dir}/BUILDROOT" \
                --dbpath ${HOME}/.rpmdb \
                --target ${rpm_arch} \
                -bb ${spec_dir}/${PROJECT_NAME}.spec; then
        # 复制到dist目录
        if ls ${rpmbuild_dir}/${rpm_arch}/*.rpm >/dev/null 2>&1; then
            cp ${rpmbuild_dir}/${rpm_arch}/*.rpm ${DIST_DIR}/${dist_subdir}/
            local rpm_file=$(ls ${rpmbuild_dir}/${rpm_arch}/*.rpm)
            echo "创建了 ${DIST_DIR}/${dist_subdir}/$(basename ${rpm_file})"
            return 0
        else
            echo "错误: RPM文件未生成"
            # 尝试从其他位置查找RPM文件
            find ${rpm_dir} -name "*.rpm" -exec cp {} ${DIST_DIR}/${dist_subdir}/ \;
            if ls ${DIST_DIR}/${dist_subdir}/*.rpm >/dev/null 2>&1; then
                echo "从其他位置找到了RPM文件"
                return 0
            else
                return 1
            fi
        fi
    else
        echo "错误: RPM构建失败"
        return 1
    fi
}

# 函数：使用fpm创建RPM包（备选方案）
create_rpm_with_fpm() {
    local arch=$1
    local rpm_arch=$2
    local dist_subdir=$3
    
    # 检查fpm是否安装
    if ! command -v fpm &> /dev/null; then
        echo "安装fpm..."
        sudo apt-get install -y ruby ruby-dev rubygems build-essential
        sudo gem install fpm
    fi
    
    # 检查可执行文件是否存在
    if [ ! -f "${BUILD_DIR}/${arch}/${PROJECT_NAME}" ]; then
        echo "错误: 未找到 ${BUILD_DIR}/${arch}/${PROJECT_NAME} 文件"
        return 1
    fi
    
    # 创建临时目录结构
    local temp_dir="${BUILD_DIR}/fpm/${arch}"
    mkdir -p ${temp_dir}/usr/bin
    mkdir -p ${temp_dir}/usr/share/doc/${PROJECT_NAME}
    
    # 复制文件
    cp ${BUILD_DIR}/${arch}/${PROJECT_NAME} ${temp_dir}/usr/bin/
    chmod 755 ${temp_dir}/usr/bin/${PROJECT_NAME}
    
    if [ -f README.md ]; then
        cp README.md ${temp_dir}/usr/share/doc/${PROJECT_NAME}/
    fi
    if [ -f LICENSE ]; then
        cp LICENSE ${temp_dir}/usr/share/doc/${PROJECT_NAME}/copyright
    fi
    
    # 使用fpm创建RPM包
    fpm -s dir -t rpm -n ${PROJECT_NAME} -v ${VERSION} \
        --architecture ${rpm_arch} \
        --maintainer "${MAINTAINER}" \
        --description "${DESCRIPTION}" \
        --license "GPL-3.0" \
        --url "https://github.com/huwenyupeter/drwtest" \
        -C ${temp_dir} \
        -p ${DIST_DIR}/${dist_subdir}/${PROJECT_NAME}-${VERSION}-1.${rpm_arch}.rpm
    
    if [ $? -eq 0 ]; then
        echo "使用fpm创建了 ${DIST_DIR}/${dist_subdir}/${PROJECT_NAME}-${VERSION}-1.${rpm_arch}.rpm"
        return 0
    else
        echo "错误: fpm创建RPM包失败"
        return 1
    fi
}

# 构建x86_64版本
echo "开始构建x86_64版本..."
if build_architecture "x86_64" "toolchain-x86_64.cmake"; then
    echo "x86_64构建成功"
else
    echo "x86_64构建失败，跳过x86_64包创建"
fi

# 构建aarch64版本
echo "开始构建aarch64版本..."
if build_architecture "aarch64" "toolchain-aarch64.cmake"; then
    echo "aarch64构建成功"
else
    echo "aarch64构建失败，跳过aarch64包创建"
fi

# 为每个架构创建包，忽略单个包的构建错误
for arch in x86_64 aarch64; do
    if [ -f "${BUILD_DIR}/${arch}/${PROJECT_NAME}" ]; then
        echo "为 ${arch} 创建包..."
        
        case $arch in
            x86_64)
                # 创建DEB包，忽略错误
                if ! create_deb_package $arch "amd64" "x86_64"; then
                    echo "警告: x86_64 DEB包创建失败，继续执行"
                fi
                
                # 创建RPM包，忽略错误
                if ! create_rpm_package $arch "x86_64" "x86_64"; then
                    echo "警告: x86_64 RPM包创建失败，继续执行"
                fi
                ;;
            aarch64)
                # 创建DEB包，忽略错误
                if ! create_deb_package $arch "arm64" "aarch64"; then
                    echo "警告: aarch64 DEB包创建失败，继续执行"
                fi
                
                # 首先尝试使用标准方法创建RPM包
                if ! create_rpm_package $arch "aarch64" "aarch64"; then
                    echo "标准RPM构建失败，尝试使用fpm创建aarch64 RPM包..."
                    # 使用fpm作为备选方案
                    if ! create_rpm_with_fpm $arch "aarch64" "aarch64"; then
                        echo "警告: aarch64 RPM包创建失败，继续执行"
                    fi
                fi
                ;;
        esac
    else
        echo "警告: 未找到 ${arch} 架构的构建文件，跳过包创建"
    fi
done

echo "=== 在Kali Linux上的构建和打包完成 ==="
echo "发布文件位于: ${DIST_DIR}/"
echo "x86_64架构包:"
ls -la ${DIST_DIR}/x86_64/ 2>/dev/null || echo "x86_64目录为空或不存在"
echo "aarch64架构包:"
ls -la ${DIST_DIR}/aarch64/ 2>/dev/null || echo "aarch64目录为空或不存在"

# 显示安装说明
echo ""
echo "安装说明:"
if [ -f "${DIST_DIR}/x86_64/${PROJECT_NAME}_${VERSION}_amd64.deb" ]; then
    echo "x86_64 DEB包安装: sudo dpkg -i ${DIST_DIR}/x86_64/${PROJECT_NAME}_${VERSION}_amd64.deb"
fi
if [ -f "${DIST_DIR}/x86_64/${PROJECT_NAME}-${VERSION}-1.x86_64.rpm" ]; then
    echo "x86_64 RPM包安装: sudo rpm -i ${DIST_DIR}/x86_64/${PROJECT_NAME}-${VERSION}-1.x86_64.rpm"
fi
if [ -f "${DIST_DIR}/aarch64/${PROJECT_NAME}_${VERSION}_arm64.deb" ]; then
    echo "aarch64 DEB包安装: sudo dpkg -i ${DIST_DIR}/aarch64/${PROJECT_NAME}_${VERSION}_arm64.deb"
fi
if [ -f "${DIST_DIR}/aarch64/${PROJECT_NAME}-${VERSION}-1.aarch64.rpm" ]; then
    echo "aarch64 RPM包安装: sudo rpm -i ${DIST_DIR}/aarch64/${PROJECT_NAME}-${VERSION}-1.aarch64.rpm"
fi
